package com.itchen.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author げっしょく
 * @date 2021/9/4
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        String[] s = {"/login.jsp","/register.jsp", "/css/", "/imgs/", "/loginUser", "/addUser", "/checkCodeServlet"};
        HttpServletRequest request = (HttpServletRequest) req;

        StringBuffer requestURL = request.getRequestURL();
        String URL = requestURL.toString();


        for (String s1 : s) {
            System.out.println("s1:"+s1);
            if (URL.contains(s1)) {
                System.out.println("111111111111111111111111");
                chain.doFilter(req, resp);
                return;
            }
        }



        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user != null) {
            chain.doFilter(req, resp);
        } else {
            req.setAttribute("login_msg", "请先登录");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
